﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;

namespace HisGL
{
    public class ComonHelper
    {
        public static T ToConvert<T>(DataRow dr, string sField, T tDef)
        {
            T sResult = tDef;
            object jt = dr[sField]; 
            if (jt == null)
            {
                sResult = tDef;
            }
            else if (tDef is int)
            {
                if (jt.ToString().Trim() == "")
                    sResult = tDef;
                else
                    sResult = (T)(object)(Convert.ToInt32(jt.ToString().Trim()));
            }
            else if (tDef is double)
            {
                if (jt.ToString().Trim() == "")
                    sResult = tDef;
                else
                    sResult = (T)(object)(Convert.ToDouble(jt.ToString().Trim()));
            }
            else if (tDef is float)
            {
                if (jt.ToString().Trim() == "")
                    sResult = tDef;
                else
                    sResult = (T)(object)(Convert.ToDouble(jt.ToString().Trim()));
            }
            else if (tDef is bool)
            {
                if (jt.ToString().Trim() == "")
                    sResult = tDef;
                else
                    sResult = (T)(object)(jt.ToString().Trim() == "1" || jt.ToString().ToLower().Trim() == "true");
            }
            else
            {
                sResult = (T)(object)(jt.ToString().Trim());
            }
            return sResult;
        }


        public static T ToConvert<T>(object val, T tDef)
        {
            T sResult = tDef;
            if (val == null)
            {
                sResult = tDef;
            }
            else
            {
                sResult = (T)val;
            }
            return sResult;
        }

        #region date

        public static int DateToInt(DateTime date)
        {
            //Delphi的初始化日期是:1899-12-30
            DateTime beginDate = new DateTime(1899, 12, 30);
            TimeSpan timeSpan = date - beginDate;
            return timeSpan.Days;
        }

        public static string DateToStr(DateTime date)
        {
            string result = date.ToString("yyyy-MM-dd");
            if (result == "1899-12-30")
                result = "";
            return result;
        }

        public static string DateToStr(DateTime date, string fotmat)
        {
            string result = date.ToString(fotmat);
            if (result == "18991230")
                result = "";
            return result;
        }

        public static DateTime StrToDate(string s)
        {
            return DateTime.Parse(s.Trim());
        }

        public static DateTime StrToDate(string date, string fotmat)
        {
            if (fotmat.Length == 0)
            {
                fotmat = "yyyyMMdd";
            }
            return DateTime.ParseExact(date, fotmat, System.Globalization.CultureInfo.CurrentCulture);
        }

        public static int StrToTime(string s)
        {
            int hour = Int32.Parse(ExtractString(s, 1, ":"));
            int minute = Int32.Parse(ExtractString(s, 2, ":"));
            return hour * 3600 + minute * 60;
        }

        public static string TimeToStr(DateTime date)
        {
            return date.ToString("HH:mm");
        }

        public static int TimeToInt(DateTime date)
        {
            return date.Hour * 3600 + date.Minute * 60 + date.Second;
        }

        public static string IntToDateStr(int date)
        {
            //Delphi的初始化日期是:1899-12-30
            string result = "";
            DateTime beginDate = new DateTime(1899, 12, 30);
            TimeSpan timeSpan = new TimeSpan(date, 0, 0, 0, 0);
            result = (beginDate + timeSpan).ToString("yyyy-MM-dd");
            return result;
        }

        public static string IntToTimeStr(int value)
        {
            int h = value / 3600;
            int m = (value % 3600) / 60;
            int s = (value % 60);
            return String.Format("{0}:{1:D2}", h, m);
        }

        public static DateTime IntToDate(int date)
        {
            //Delphi的初始化日期是:1899-12-30
            DateTime beginDate = new DateTime(1899, 12, 30);
            TimeSpan timeSpan = new TimeSpan(date, 0, 0, 0, 0);
            return (beginDate + timeSpan);

        }

        public static int DateToAgeInt(int birthday)
        {
            int v, nl, refrenceDay;
            if (birthday == 0)
            {
                return 0;
            }
            refrenceDay = DateToInt(DateTime.Today);
            v = refrenceDay - birthday;
            nl = v / 365;
            return nl;
        }

        public static string DateToAge(int csrq)
        {
            if (csrq == 0)
                return "";

            DateTime today = DateTime.Today;
            DateTime birthday = IntToDate(csrq);
            if (today.Year == birthday.Year)
            {
                if (today.Month == birthday.Month)
                {
                    int day = today.Day - birthday.Day;
                    if (day > 0)
                        return day.ToString() + "天";
                    else
                        return "";
                }

                int month = today.Month - birthday.Month;
                return month.ToString() + "月";
            }

            int y = today.Year - birthday.Year;
            return y.ToString() + "岁";

        }

        /// <summary>
        /// 计算年龄
        public static DateSpan DateToAge(DateTime dCSRQ, DateTime dBJRQ)
        {
            //判断时间段是否为正。若为负，调换两个时间点的位置。
            System.DateTime p_FirstDateTime = dCSRQ;
            System.DateTime p_SecondDateTime = dBJRQ;
            if (System.DateTime.Compare(p_FirstDateTime, dBJRQ) > 0)
            {
                System.DateTime stmpDateTime = p_FirstDateTime;
                p_FirstDateTime = p_SecondDateTime;
                p_SecondDateTime = stmpDateTime;
            }
 
            //定义：年、月、日
            int year, month, day;

            //计算：天
            day = p_SecondDateTime.Day - p_FirstDateTime.Day;
            if (day < 0)
            {
                day += System.DateTime.DaysInMonth(p_FirstDateTime.Year, p_FirstDateTime.Month);
                p_FirstDateTime = p_FirstDateTime.AddMonths(1);
            }
            //计算：月
            month = p_SecondDateTime.Month - p_FirstDateTime.Month;
            if (month < 0)
            {
                month += 12;
                p_FirstDateTime = p_FirstDateTime.AddYears(1);
            }
            //计算：年
            year = p_SecondDateTime.Year - p_FirstDateTime.Year;

            DateSpan res = new DateSpan();
            res.Year = year;
            res.Month = month;
            res.Day = day;

            return res;
        }


        public static int MonthOfDate(int date)
        {
            DateTime d = IntToDate(date);
            return d.Month;
        }

        public static int YearOfDate(int date)
        {
            DateTime d = IntToDate(date);
            return d.Year;
        }

        public static int DayOfDate(int date)
        {
            DateTime d = IntToDate(date);
            return d.Day;
        }

        public static int FirstDayOfMonth(int date)
        {
            DateTime d = IntToDate(date);
            DateTime firstDay = new DateTime(d.Year, d.Month, 1);
            return DateToInt(firstDay);
        }

        public static int LastDayOfMonth(int date)
        {
            DateTime d = IntToDate(date);
            DateTime firstDay = new DateTime(d.Year, d.Month, 1);

            DateTime lastDay = firstDay.AddMonths(1).AddDays(-1);
            return DateToInt(lastDay);
        }

        public static DateTime FirstDayOfMonth(DateTime date)
        {
            DateTime firstDay = new DateTime(date.Year, date.Month, 1);
            return firstDay;
        }

        public static DateTime LastDayOfMonth(DateTime date)
        {
            DateTime firstDay = new DateTime(date.Year, date.Month, 1);
            DateTime lastDay = firstDay.AddMonths(1).AddDays(-1);
            return lastDay;
        }

        #endregion

        //index: 取第一组字符串则应该把index设置成1，如此类推
        public static string ExtractString(string text, int index, string divString)
        {
            List<string> list = new List<string>();
            string S = text.Trim();
            string tmpStr = null;
            int i;
            i = S.IndexOf(divString);
            while (i >= 0)
            {
                tmpStr = S.Substring(0, i);
                list.Add(tmpStr.Trim());
                S = S.Remove(0, i + divString.Length);
                S = S.Trim();
                i = S.IndexOf(divString);
            }
            if (S.Length > 0)
            {
                list.Add(S.Trim());
            }
            if (index <= list.Count)
                return list[index - 1];
            else
                return "";
        }

        /// <summary>
        /// Csv文件转DataTable，第一行是字段名
        /// </summary>
        /// <param name="fileFullPath"></param>
        /// <returns></returns>
        public static DataTable CsvToDataTable(string fileFullPath)
        {
            int intColCount = 0;
            bool blnFlag = true;
            DataTable mydt = new DataTable("myTableName");
            DataColumn mydc;
            DataRow mydr;
            string strpath = fileFullPath; //cvs文件路径
            string strline;
            string[] aryline;
            System.IO.StreamReader mysr = new System.IO.StreamReader(strpath, Encoding.Default);
            while ((strline = mysr.ReadLine()) != null)
            {
                List<string> ss = new List<string>();
                aryline = strline.Split(new char[] { ',' });
                if (strline.IndexOf("\"") > -1)
                {
                    for (int i = 0; i < aryline.Length; i++)
                    {
                        if (aryline[i].Contains("\""))
                        {
                            ss.Add(aryline[i] + "," + aryline[++i]);
                            if (i == aryline.Length - 1)
                            {
                                break;
                            }
                        }
                        else
                        {
                            ss.Add(aryline[i]);
                        }
                    }
                }
                else
                {
                    ss.AddRange(aryline);
                }
                if (blnFlag)
                {
                    blnFlag = false;
                    intColCount = ss.Count;
                    for (int i = 0; i < intColCount; i++)
                    {
                        mydc = new DataColumn(ss[i]);
                        mydt.Columns.Add(mydc);
                    }
                }
                else
                {
                    mydr = mydt.NewRow();
                    int iCols = intColCount;
                    if (iCols > ss.Count)
                    {
                        iCols = ss.Count;
                    }

                    for (int i = 0; i < iCols; i++)
                    {
                        mydr[i] = ss[i];
                    }
                    mydt.Rows.Add(mydr);
                }


            }
            return mydt;
        }

        /// <summary>
        /// 逐行读取，包含空行
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static List<string> SplitByLine(string text)
        {
            List<string> lines = new List<string>();
            byte[] array = Encoding.UTF8.GetBytes(text);
            using (MemoryStream stream = new MemoryStream(array))
            {
                using (var sr = new StreamReader(stream))
                {
                    string line = sr.ReadLine();
                    while (line != null)
                    {
                        lines.Add(line);
                        line = sr.ReadLine();
                    };
                }

            }
            return lines;
        }
    }

    public struct DateSpan
    {
        public int Year { get; set; }

        public int Month { get; set; }

        public int Day { get; set; }
    }
}
